import { Link, useNavigate } from "react-router-dom";
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Select,
  Popconfirm,
} from "antd";
//引入汉化包
// import "moment/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";
import "./index.scss";

import { Table, Tag, Space } from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";

import img404 from "../../assets/error.png";
import { useChannel } from "../../hooks/useChannel";
import { useEffect, useState, JSX } from "react";
import {
  getArticleAPI,
  deleteArticleAPI,
  type ArticleType,
} from "../../apis/article";
import { Dayjs } from "dayjs";

const { Option } = Select;
const { RangePicker } = DatePicker;

const Article = () => {
  // console.log("📦 Article 组件渲染");

  const { channelList } = useChannel();
  const articleStatus: Record<number, JSX.Element> = {
    1: <Tag color="warning">待审核</Tag>,
    2: <Tag color="green">审核通过</Tag>,
  };
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      width: 120,
      render: (cover: ArticleType["cover"]) => {
        return (
          <img src={cover.images[0] || img404} width={80} height={60} alt="" />
        );
      },
    },
    {
      title: "标题",
      dataIndex: "title",
      width: 220,
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (status: number) => {
        return articleStatus[status];
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
    },
    {
      title: "操作",
      render: (data: ArticleType) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => navigate(`/publish?id=${data.id}`)}
            />
            <Popconfirm
              title="删除文章"
              description="确认删除吗？"
              onConfirm={() => onConfirm(data)}
              // onCancel={cancel}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  // const data = [
  //   {
  //     id: "8218",
  //     comment_count: 0,
  //     cover: {
  //       images: ["http://geek.itheima.net/resources/images/15.jpg"],
  //     },
  //     like_count: 0,
  //     pubdate: "2019-03-11 09:00:00",
  //     read_count: 2,
  //     status: 2,
  //     title: "wkwebview离线化加载h5资源解决方案",
  //   },
  // ];
  // 筛选功能
  //1.准备参数
  const [reqData, setReqData] = useState({
    status: "",
    channel_id: "",
    begin_pubdate: "",
    end_pubdate: "",
    page: 1,
    per_page: 4,
  });

  //获取文章列表
  const [articleList, setArticleList] = useState<ArticleType[]>([]);
  const [articleCount, setArticleCount] = useState(0);

  useEffect(() => {
    async function getArticleList() {
      const res = await getArticleAPI(reqData);
      setArticleList(res.data.results);
      setArticleCount(res.data.total_count);
    }
    getArticleList();
  }, [reqData]);

  // 筛选功能

  //2.获取选择的表单数据
  const onFinish = (formValues: {
    status: string;
    channel_id: string;
    date: [Dayjs, Dayjs];
  }) => {
    console.log(formValues);
    //3.放到接口中
    setReqData({
      ...reqData,
      channel_id: formValues.channel_id,
      status: formValues.status,
      begin_pubdate: formValues.date[0].format("YYYY-MM-DD"),
      end_pubdate: formValues.date[1].format("YYYY-MM-DD"),
    });
    //4.重新拉取列表+渲染table逻辑
    //reqData依赖项发生变化，重复执行effect（依赖项）
  };

  //分页功能
  const onPageChange = (page: number) => {
    setReqData({
      ...reqData,
      page,
    });
  };

  //删除文章按钮
  const onConfirm = async (data: ArticleType) => {
    await deleteArticleAPI(data.id);
    setReqData({
      ...reqData,
    });
  };

  //编辑文章跳转
  const navigate = useNavigate();

  return (
    <div>
      <Card
        title={
          <Breadcrumb
            separator=">"
            items={[
              { title: <Link to="/home">首页</Link> },
              { title: "内容管理" },
            ]}
          />
        }
        // style={{ marginBottom: 20 }}
      >
        <Form
          initialValues={{
            status: "",
            username: "默认用户名",
            email: "default@example.com",
          }}
          onFinish={onFinish}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={""}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择文章频道"
              // defaultValue="lucy"
              style={{ width: 120 }}
            >
              {channelList.map((value) => (
                <Option value={value.id} key={value.id}>
                  {value.name}
                </Option>
              ))}
              {/* <Option value="jack">Jack</Option>
              <Option value="lucy">Lucy</Option> */}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 80 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* //表格区域 */}
      <Card title={`根据筛选条件共查询到 ${articleCount} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={articleList}
          pagination={{
            total: articleCount,
            pageSize: reqData.per_page,
            onChange: onPageChange,
          }}
        />
      </Card>
    </div>
  );
};

export default Article;
